﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class BusRoutes : ClassManager.SessionManagerPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = "BusRouteIdSource.Name";
                expression.SetSortOrder("Ascending");
                this.BusRoutesGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_miniError", "objWindowsMessageManager.show_miniError('" + msg + "','Rutas...');", true);
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        private void GetBusRoutesByCompanyID()
        {
            GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.BusRouteByCompanies> BusRouteByCompaniesEntity = GPSTrackingDBV2.Data.DataRepository.BusRouteByCompaniesProvider.GetByCompanyId(getSessionManager().CompanyIDSelectedComboBox);
            GPSTrackingDBV2.Data.DataRepository.BusRouteByCompaniesProvider.DeepLoad(BusRouteByCompaniesEntity, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.BusRoutes));

            BusRoutesGrid.DataSource = BusRouteByCompaniesEntity;
        }

        protected void BusRoutesGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetBusRoutesByCompanyID();
            BusRoutesGrid.Height = Unit.Parse(HiddenFieldHeight.Value.ToString());
        }

        private GPSTrackingDBV2.Entities.BusRoutes Invoke_Entity(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.BusRoutes BusRoutesEntity = new GPSTrackingDBV2.Entities.BusRoutes();
            BusRoutesEntity.BusRouteId = int.Parse(Entity["BusRouteId"].ToString());
            BusRoutesEntity.Name = Entity["BusRouteIdSource.Name"].ToString();

            return BusRoutesEntity;
        }

        protected void BusRoutesGrid_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();

                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                Entity["BusRouteId"] = GPSTrackingDBV2Custom.Data.DataRepository.BusRoutesProvider.GetNextID();

                GPSTrackingDBV2.Entities.BusRoutes BusRoutesEntity = Invoke_Entity(Entity);

                GPSTrackingDBV2.Data.DataRepository.BusRoutesProvider.Insert(tm, BusRoutesEntity);

                GPSTrackingDBV2.Entities.BusRouteByCompanies BusRouteByCompaniesEntity = new GPSTrackingDBV2.Entities.BusRouteByCompanies();
                BusRouteByCompaniesEntity.BusRouteId = BusRoutesEntity.BusRouteId;
                BusRouteByCompaniesEntity.CompanyId = getSessionManager().CompanyIDSelectedComboBox;

                GPSTrackingDBV2.Data.DataRepository.BusRouteByCompaniesProvider.Insert(tm, BusRouteByCompaniesEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede registrar la ruta.");
            }
        }

        protected void BusRoutesGrid_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.BusRoutes BusRoutesEntity = Invoke_Entity(Entity);
                BusRoutesEntity.OriginalBusRouteId = int.Parse(Entity["BusRouteId"].ToString());

                GPSTrackingDBV2.Data.DataRepository.BusRoutesProvider.Update(tm, BusRoutesEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede actualizar la ruta.");
            }
        }

        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void BusRoutesGrid_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();

                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.BusRoutes BusRoutesEntity = Invoke_Entity(Entity);

                //GPSTrackingDBV2Custom.Data.DataRepository.BusRoutesProvider.Delete(objInfoShared.CompanyID, BusRoutesEntity.BusRouteId);
                GPSTrackingDBV2.Data.DataRepository.BusRouteByCompaniesProvider.Delete(tm, getSessionManager().CompanyIDSelectedComboBox, BusRoutesEntity.BusRouteId);
                GPSTrackingDBV2.Data.DataRepository.BusRoutesProvider.Delete(tm, BusRoutesEntity);

                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                
                if (ex.Message.Contains("FK_BusRoutesDetails_BusRoutes"))
                    showErrorMessage("No se puede eliminar la ruta porque ya tiene asociado puntos de Ruta, debe eliminarla desde el mapa");
                else
                    if (ex.Message.Contains("FK_BusStopByBusRoutes_BusRoutes"))
                        showErrorMessage("No se puede eliminar la ruta porque ya tiene asociado puntos de Paradas, debe eliminar los puntos desde el mapa");
                    else
                        showErrorMessage("No se puede eliminar la ruta porque esta asociado a otros registros.");
            }
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            BusRoutesGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in BusRoutesGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            BusRoutesGrid.MasterTableView.Rebind();
        }

    }
}